package de.fhhannover.inform.itteam.snmpnetviz;

import java.util.Iterator;

import prefuse.data.Node;
import prefuse.data.Tree;

public class TreeConverter {
	public static Tree getTreeForHostEntryTree(HostEntry root) {
		Tree tree = new Tree();
		
		tree.getNodeTable().addColumn("ip", String.class);
		tree.getNodeTable().addColumn("name", String.class);
		tree.getNodeTable().addColumn("domain", String.class);
		tree.getNodeTable().addColumn("mac", String.class);
		tree.getNodeTable().addColumn("vlan", int.class);
		tree.getNodeTable().addColumn("port", int.class);
		tree.getNodeTable().addColumn("portdesc", String.class);
		tree.getNodeTable().addColumn("type", String.class);
		
		Node treeRoot = tree.addRoot();
		setNodeAttributes(treeRoot, root);
		
		addChildTree(tree, treeRoot, root);
		
		return tree;
	}
	
	private static void addChildTree(Tree tree, Node cnode, HostEntry start) {
		if (start.hasChildren()) {
			Iterator<HostEntry> it = start.getChildren();
			while(it.hasNext()) {
				HostEntry current = it.next();
				
				if (current.getIpAddress()!=null) {
					if (start.getParent()==null || !start.getParent().getIpAddress().equals(current.getIpAddress())) {
						Node node = tree.addChild(cnode);
						setNodeAttributes(node, current);
						
						addChildTree(tree, node, current);
					}
				}				
			}
		}
	}
	
	/**
	 * copy the attribute from the HostEntry to the Node attributes
	 */
	private static void setNodeAttributes(Node node, HostEntry host) {
		node.setString("ip", host.getIpAddress());
		node.setString("name", host.getName());
		node.setString("domain", host.getDomain());
		node.setString("mac", host.getMacAddress());
		node.setInt("vlan", host.getVlan());
		node.setInt("port", host.getPort());
		node.setString("portdesc", host.getPortDescription());
		if (host.isSwitch()) node.setString("type", "switch");
		else node.setString("type", "host");
	}
}
